<template>
    <div class="user-list-wrap display-flex flex-column">
      <div class="panel panel-form">
        <el-form :inline="true" class="filter-form">
          <div class="form-content">
            <el-form-item label="姓名">
              <el-input v-model="queryParams.username" clearable placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="queryParams.phone" clearable placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="用户权限">
              <el-select v-model="queryParams.manageType" placeholder="请选择用户权限" clearable>
                <el-option v-for="(val, key) in manageType" :key="key" :label="val" :value="key" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-button @click="resetFilterForm()">重置</el-button>
            <el-button type="primary" @click="getList(1)">查询</el-button>
          </div>
        </el-form>
      </div>
      <div class="panel flex flex-column table-container" style="padding-bottom: 0">
        <div class="table-btns">
          <el-button type="primary" @click="userAdd()">新增用户</el-button>
        </div>
        <el-table v-loading="loading" :border="true" :data="tableData"  height="100%" :header-cell-style="{background:'#D8E8FF'}">
          <el-table-column type="index" label="序号" min-width="50" align="center" />
          <el-table-column prop="username" label="姓名" width="150" align="center" />
          <el-table-column prop="phone" label="注册手机号" min-width="150" align="center" />
          <el-table-column prop="manager" label="权限" min-width="150" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.is_manager===0" type="warning" size="small">{{manageType[scope.row.is_manager]}}</el-tag>
              <el-tag v-if="scope.row.is_manager===10" type="success" size="small">{{manageType[scope.row.is_manager]}}</el-tag>
              <el-tag v-if="scope.row.is_manager===20" type="danger" size="small">{{manageType[scope.row.is_manager]}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="150" align="center">
            <template slot-scope="scope">
              <span :class="['status', { active: scope.row.is_use == 10 }]">
                {{
                  scope.row.is_use == 10 ? "启用" : "禁用"
                }}
              </span>
              <el-switch
                v-model="scope.row.is_use"
                :active-value="10"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#C0CCDA"
                @change="statucChange(scope.row)"
                :disabled="useEditJudge(scope.row.is_manager)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" min-width="300" align="center">
            <template slot-scope="scope">
              <el-button type="primary" plain @click="updateUser(scope.row)" :disabled="useEditJudge(scope.row.is_manager)">修改信息</el-button>
              <el-button type="primary" plain @click="resetPassword(scope.row)" :disabled="useEditJudge(scope.row.is_manager)">重置密码</el-button>
              <el-button type="primary" plain @click="handleRmoveUser(scope.row)" :disabled="useEditJudge(scope.row.is_manager)">移除</el-button>
              <el-button type="primary" plain @click="handleRmoveUser(scope.row)" :disabled="useEditJudge(scope.row.is_manager)">修改权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <pagination-control
            :paging-params="pagingParams"
            @onCurrentPage="handleCurrentChange"
            @onCurrentSize="handleSizeChange"
          />
        </div>
      </div>
  
      <el-dialog title="修改用户" :close-on-click-modal="false" :visible.sync="updateUserShow" width="540px">
        <div class="dialog-content">
          <el-form ref="updateUserFormEle" :model="updateUserForm" label-width="120px">
            <el-form-item label="姓名" prop="username" :rules="[{ required: true, message: '请输入姓名' }]">
              <el-input v-model="updateUserForm.username" clearable placeholder="请输入姓名"  />
            </el-form-item>
            <el-form-item label="注册手机号" prop="phone" :rules="[{ required: true, message: '请输入注册手机号' }]">
              <el-input
                v-model="updateUserForm.phone"
                clearable
                placeholder="请输入注册手机号"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item label="用户身份" prop="user_role" :rules="[{ required: true, message: '请选择用户身份' }]">
              <el-select v-model="updateUserForm.user_role" placeholder="请选择用户身份" clearable>
                <el-option v-for="(val, key) in roleList" :key="key" :label="val" :value="key*1" />
              </el-select>
            </el-form-item>
            <el-form-item label="入学年份" prop="enrollment_year" :rules="[{ required: true, message: '请输入入学年份' }]" v-if="updateUserForm.user_role==20||updateUserForm.user_role==30||updateUserForm.user_role==40||updateUserForm.user_role==50">
              <el-date-picker
                v-model="updateUserForm.enrollment_year"
                type="year"
                value-format="yyyy"
                placeholder="入学年份"
              />
            </el-form-item>
            <el-form-item prop="manager" label="管理员角色" width="150" >
              <el-switch
                v-model="updateUserForm.is_manager"
                :active-value="10"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#C0CCDA"
              />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateUserShow = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdateUser">确定</el-button>
        </span>
      </el-dialog>
  
      <el-dialog title="新增用户" :close-on-click-modal="false" :visible.sync="userAddShow" width="540px">
        <div class="dialog-content">
          <el-form ref="addUserFormEle" :model="userAddParam" label-width="120px">
            <el-form-item label="姓名" prop="username" :rules="[{ required: true, message: '请输入姓名' }]">
              <el-input v-model="userAddParam.username" clearable placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="注册手机号" prop="phone" :rules="[{ required: true, message: '请输入注册手机号' }]">
              <el-input
                v-model="userAddParam.phone"
                clearable
                placeholder="请输入注册手机号"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item label="用户身份" prop="user_role" :rules="[{ required: true, message: '请选择用户身份' }]">
              <el-select v-model="userAddParam.user_role" placeholder="请选择用户身份" clearable>
                <el-option v-for="(val, key) in roleList" :key="key" :label="val" :value="key*1" />
              </el-select>
            </el-form-item>
            <el-form-item label="入学年份" prop="enrollment_year" :rules="[{ required: true, message: '请输入入学年份' }]" v-if="userAddParam.user_role==20||userAddParam.user_role==30||userAddParam.user_role==40||userAddParam.user_role==50">
              <el-date-picker
                v-model="userAddParam.enrollment_year"
                type="year"
                value-format="yyyy"
                placeholder="入学年份"
              />
            </el-form-item>
            <el-form-item prop="manager" label="管理员角色" width="150" >
              <el-switch
                v-model="userAddParam.is_manager"
                :active-value="10"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#C0CCDA"
              />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userAddShow = false">取消</el-button>
          <el-button type="primary" @click="confirmAddUser">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {get, post} from "@/utils/http"
  // import { apiRoleList, apiCompanyList, apiOrgList } from '@/api/Common';
  // import { deepClone } from '@/utils/index';
  // import areaCascader from '@/components/areaCascader';
  import PaginationControl from "@/layout/paginationControl.vue"
  
  export default {
    // name: 'UserList',
    components: {
      PaginationControl
    },
    data: function() {
      return {
        user_manage: this.$store.getters.manageType,
        tableData: null,
        queryParams: {
          username: '',
          role_id: '',
          phone: ''
        },
        pagingParams: {
          page: 1,
          size: 20,
          total: 0
        },
        row: null,
        userAddParam: {
          username: '',
          phone: '',
          user_role: 0,
          is_use: 0,
          is_manager: 0,
          enrollment_year: '',
        },
        userAddShow: false,
        updateUserForm: {
          username: '',
          phone: '',
          user_role: 0,
          is_use: 0,
          is_manager: 0,
          enrollment_year: ''
        },
        updateUserShow: false,
        loading: false,
        roleList: {
          10: "教授",
          20: "在读博士",
          30: "在读硕士",
          40: "已毕业学生",
          50: "本科生（保研）"
        },
        manageType: {
          0: "查看者",
          10: "运维人员",
          20: "管理员",
        },
      };
    },
    watch: {
      // 'queryParams.role_id': function(val) {
      //   this.getList(1);
      // },
      // 'queryParams.company_id': function(val) {
      //   if (val) {
      //     apiOrgList({
      //       company_id: val
      //     }).then((res) => {
      //       this.orgList = res.data;
      //     });
      //   } else {
      //     this.orgList = null;
      //   }
      // },
      // 'updateUserForm.company_id': function(val) {
      //   if (val) {
      //     apiOrgList({
      //       company_id: val
      //     }).then((res) => {
      //       this.orgList2 = res.data;
      //     });
      //   } else {
      //     this.orgList2 = null;
      //   }
      // }
    },
    created() {
      this.getList();
    },
    methods: {
      useEditJudge(val) {
        if (this.user_manage != 20 && val > 0) {
          return true
        } else {
          return false
        }
      },
      resetFilterForm() {
        for (const key in this.queryParams) {
          this.queryParams[key] = '';
        }
        this.getList(1);
      },
      getList(isReset) {
        if (isReset) {
          this.pagingParams.page = 1;
        }
        get("/user/manage/list?page="+this.pagingParams.page +"&size="+this.pagingParams.size+"&phone="+this.queryParams.phone+"&username="+this.queryParams.username+"&role_id="+this.queryParams.role_id)
        .then(res=>{
          console.log(res.data.data)
          this.tableData = res.data.data.list;
          this.pagingParams.total = res.data.data.count;
        })
      },
      handleCurrentChange(val) {
        this.pagingParams.page = val;
        this.getList();
      },
      handleSizeChange(val) {
        this.pagingParams.size = val;
        this.getList(1);
      },
      statucChange(row) {
        console.log(row.id)
        get("/user/manage/is-use?user_id="+row.id+"&is_use="+row.is_use)
        .then(res=>{
          console.log(res)
          if (res.data.code != 0) {
            this.$message.error(res.data.message)
          }
          this.getList();
        })
      },
      userAdd(){
        for (const key in this.userAddParam) {
          this.userAddParam[key] = '';
        }
        this.userAddShow = true;
        this.$nextTick(() => {
          this.$refs.addUserFormEle.clearValidate();
        });
      },
      handleRmoveUser(row) {
        this.$confirm('确认移除该用户？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          get("/user/manage/delete?user_id="+row.id)
          .then(res=>{
            this.getList();
          })
        });
      },
      updateUser(row) {
        this.row = row;
        for (const key in this.updateUserForm) {
          console.log(key)
          console.log(this.updateUserForm[key])
          this.updateUserForm[key] = row ? row[key] : '';
        }
        this.updateUserForm.enrollment_year = String(this.updateUserForm.enrollment_year)
        this.updateUserShow = true;
        this.$nextTick(() => {
          this.$refs.updateUserFormEle.clearValidate();
        });
      },
      confirmUpdateUser() {
        this.$refs.updateUserFormEle.validate((valid) => {
          if (valid) {
            let params = this.deepClone(this.updateUserForm);
            console.log("11111111111")
            params.user_id = this.row.id;
            params.user_role = new Number(params.user_role)
            params.enrollment_year = new Number(params.enrollment_year)
            post("/user/manage/edit", params)
            .then(res=>{
              if(res.data.code == 0) {
                this.$message.success(`修改成功`);
                this.updateUserShow = false;
                this.getList();
              }
            })
          }
        });
      },
      confirmAddUser() {
        this.$refs.addUserFormEle.validate((valid) => {
          if (valid) {
            let params = this.deepClone(this.userAddParam);
            console.log("11111111111")
            params.user_role = new Number(params.user_role)
            params.is_use = 10
            params.enrollment_year = new Number(params.enrollment_year)
            console.log(params.user_role)
            post("/user/manage/add", params)
            .then(res=>{
              if(res.data.code == 0) {
                this.$message.success(`新增成功`);
                this.userAddShow = false;
                this.getList();
              }
            })
          }
        });
      },
      deepClone(source) {
        if (!source && typeof source !== 'object') {
          throw new Error('error arguments', 'deepClone');
        }
        const targetObj = source.constructor === Array ? [] : {};
        Object.keys(source).forEach((keys) => {
          if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys]);
          } else {
            targetObj[keys] = source[keys];
          }
        });
        return targetObj;
      },
      resetPassword(row) {
        this.$confirm('确认重置该用户密码？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          get("/user/password-reset?user_id="+row.id)
          .then((res) => {
            if (res.data.code == 0) {
              this.$message({
                type: 'success',
                message: '重置成功!'
              });
            }
          })
        });
      },
    }
  };
  </script>
  
  <style lang="less" scoped>
  .user-list-wrap {
      height: 100%;
      width: 100%;
    position: relative;
      .status {
          color: #c0ccda;
          margin-right: 8px;
          &.active {
              color: #13ce66;
          }
      }
    .manager {
          color: #c0ccda;
          margin-right: 8px;
          &.active {
              color: #13ce66;
          }
      }
    .table-container {
      position: absolute;
      left: 0;
      right: 0;
      top: 90px;
      bottom: 0;
      .el-table {
        font-size: 12px !important;
      }
    }
      .panel {
          box-shadow: 0 0 5px #ebe7e7;
          background-color: #fff;
          padding: 20px;
          overflow: hidden;
      display: flex;
      flex-direction: column;
          
          .table-btns {
              display: flex;
              justify-content: flex-end;
              margin-bottom: 10px;
          }
      }
      .filter-form {
          display: flex;
          align-items: center;
          .form-content {
              flex: 1;
              margin-right: 20px;
              margin-top: -6px;
              margin-bottom: -6px;
          }
      }
      ::v-deep {
          .filter-form {
              .el-form-item {
                  margin-bottom: 0;
                  padding-top: 6px;
                  padding-bottom: 6px;
              }
              .el-form-item__label {
                  font-size: 12px;
                  font-weight: normal;
              }
        .el-input--suffix .el-input__inner {
          height: 32px;
        }
          }
          .dialog-content {
              .el-select,
              .el-input {
                  width: 300px;
              }
          }
      }
  }
  .el-button{
    border-radius: 16px;
    font-size: 12px;
    padding: 9px 15px;
    &.el-button--primary.is-plain{
      color: #409EFF;
      background: #E9F2FF;
      border: 1px solid #C4E1FF;
    }
    &.el-button--danger.is-plain{
      color: #FF9D9D;
      background: #FDEEEE;
      border: 1px solid #FFD4D4;
    }
  }
  //表格内容颜色
  ::v-deep .el-table__body tbody tr:nth-child(odd) {
    background-color: #FFFFFF;
  }
  ::v-deep .el-table__body tbody tr:nth-child(even) td {
    background-color: #F1F8FF;
  }
  //表头文字样式
  ::v-deep .el-table__header-wrapper {
    thead {
      th{
        div{
          // font-weight: 700;
          // font-size: 20px;
          color: #333333
        }
      }
    }
  }
  
  </style>
  